package com.ruoyi.framework.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.cache.Cache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Mybatis - redis二级缓存
 *
 * @author luohq
 * @date 2019/3/15
 */
public final class MybatisRedisCache implements Cache {
    /**
     * 日志工具类
     */
    private static final Logger logger = LogManager.getLogger(MybatisRedisCache.class);

    /**
     * 读写锁
     */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    /**
     * ID
     */
    private String id;

    /**
     * 集成redisTemplate
     */
    private static RedisTemplate redisTemplate;

    /**
     * Jackson-databind对象序列化器（核心）
     */
    private static ObjectMapper objectMapper;

    /**
     * 序列化器初始化
     */
    static {
        objectMapper = new ObjectMapper();
        //所有属性均可序列化
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        /**
         * 序列化类型信息（使用objectMapper.readValue(hashVal, Object.class)也可以实现相应类型的序列化和反序列化
         * 好处：只定义一个序列化器就可以了（通用））
         */
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    }

    public MybatisRedisCache() {
    }

    public MybatisRedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        } else {
            logger.info("MybatisRedisCache.id={}", id);
            this.id = id;
        }
    }


    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public int getSize() {
        try {
            Long size = redisTemplate.opsForHash().size(this.id.toString());
            logger.info("MybatisRedisCache.getSize: {}->{}", id, size);
            return size.intValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void putObject(final Object key, final Object value) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            String hashVal = objectMapper.writeValueAsString(value);
            logger.info("MybatisRedisCache.putObject: {}->{}->{}", id, key, hashVal);
            redisTemplate.opsForHash().put(this.id.toString(), key.toString(), hashVal);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object getObject(final Object key) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            String hashVal = (String) redisTemplate.opsForHash().get(this.id.toString(), key.toString());
            logger.info("MybatisRedisCache.getObject: {}->{}->{}", id, key, hashVal);
            if (null == hashVal) {
                return null;
            }
            return objectMapper.readValue(hashVal, Object.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Object removeObject(final Object key) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            redisTemplate.opsForHash().delete(this.id.toString(), key.toString());
            logger.info("MybatisRedisCache.removeObject: {}->{}->{}", id, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void clear() {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            redisTemplate.delete(this.id.toString());
            logger.info("MybatisRedisCache.clear: {}", id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }

    @Override
    public String toString() {
        return "MybatisRedisCache {" + this.id + "}";
    }

    private RedisTemplate getRedisTemplate() {
        if(redisTemplate == null){
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }
    /**
     * 设置redisTemplate
     *
     * @param redisTemplate
     */
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        MybatisRedisCache.redisTemplate = redisTemplate;
    }
}

